/** @format */

import { resultsModel } from '../../../sdk'
import { CODE_TYPES } from '../../../errorCode'
import { dbFindOne } from '../../common/mongodb'
import { JOIN_DB_NAME } from '../../../db'
import { findLast } from 'lodash'

export default async function checkDoLuck(context: IContext<IParams>, { activityInfo }: IControllerInfos) {
  const { lotterySwitch, probabilityConfig } = activityInfo
  if (!lotterySwitch) {
    return resultsModel.error(CODE_TYPES.PARAMS_ERROR, '抽奖未开启！')
  }
  const { openId } = context
  const { gameId } = context.data
  const joinInfo = await dbFindOne<IJoinRecord>(context, JOIN_DB_NAME, { _id: gameId })

  if (joinInfo?.openId !== openId) return resultsModel.error(CODE_TYPES.PARAMS_ERROR, `无权限抽奖！`)

  if (!joinInfo) return resultsModel.error(CODE_TYPES.SYSTEM_ERROR, '本局id不存在')

  if (joinInfo.isDraw) return resultsModel.error(CODE_TYPES.SYSTEM_ERROR, '本局提交已抽奖！')

  const probability = findLast(probabilityConfig, v => v.nowScore <= joinInfo.score)

  if (!probability) return resultsModel.error(CODE_TYPES.SYSTEM_ERROR, '未达到抽奖门槛！')

  return { joinInfo, probability }
}
